<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 订单
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
class Order extends AdminCommon {
	
	function __construct() {
		parent::__construct();
		$this->load->model('admin/Order_model','do');
	}
	
	public function index() {
		$this->do->deletes("FROM_UNIXTIME(addtime,'%Y-%m-%d') < adddate(now(),-1) and state=1");
		$data['state'] = array('2'=>'待发货','3'=>'待收货','5'=>'退货中','6'=>'关闭订单');
		$this->load->view('admin/order/index',$data);
	}
	
	function lists(){
		$srk = Gets('srk');$state = Gets('state');
		$where['state<>'] = "1";
		if($srk)$where['order_no like'] = "%$srk%";
		if($state)$where['state'] = $state;
	
		$page = Gets('page','checkid');$limit = Gets('limit','checkid');
		$total = Gets('total','num');
		
		$data = $this->do->getItems($where,'','id desc',$page,$limit,$total);
		$find = Gets('find');
		if(($srk&&$find)||!$total){
			$total = $this->do->count;
		}
		f_ajax_lists($total, $data);
	}
	
	function detail(){
		$data['exp'] = array('圆通速递','中通速递','韵达快运','优速物流','天天快递','速尔物流','顺丰','申通','如风达','汇通快运','ems快递');
		$id = Gets('id','checkid');
		$data['item'] = $this->do->getItem("id=$id");
		$this->load->view('admin/order/detail',$data);
	}
	
	//发货
	function edit(){
		if(is_ajax_request()){
			$data = Posts('data');
			$data['state'] = 3;
			$data['exp_time'] = time();
			$result = $this->do->updates($data,'id='.Posts('id','checkid'));
			is_AjaxResult($result);
		}
	}
	
	function back(){
		if(is_ajax_request()){
			$data = Posts('data');
			$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH,'notify_url'=> NOTIFY_URL]];
			$app = new Application($options);
			$result  = $app->payment->refundByTransactionId($data['wx_oid'],order_trade_no(),$data['total']*100);
			if($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
				$this->do->updates(array('state'=>4),array('id'=>$data['id']));
				AjaxResult_ok();
			}else{
				AjaxResult_error($result->return_msg.$result->err_code);
			}
		}
	}
	
	public function delete() {
		exit("不支持删除");
		$r = $this->Goods_model->deletes ( "id=" . Gets ( 'id', 'checkid' ) );
		if ($r) {
			AjaxResult_ok ();
		} else {
			AjaxResult_error ();
		}
	}
	
	
	function balance(){
		$items = $this->do->getItems("FROM_UNIXTIME(exp_time,'%Y-%m-%d') < adddate(now(),-7) and state=3",'id,uid,prices');
		if($items){
			foreach ($items as $v){
				$id[] = $v['id'];
				$fx[] = array('id'=>$v['uid'],'price'=>$v['prices']);
			}
			$id = implode(',', $id);
			$this->do->updates(array('state'=>6),"id in ($id)");
			$this->load->model(array('admin/User_model'));
			foreach ($fx as $v){
				$this->User_model->fx_fl($v['price'],$v['id']);
			}
			AjaxResult_ok('成功处理'.count($items).'订单数据');
		}else{
			AjaxResult_error('没有要处理的数据');
		}
	}
}
